<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文化知识 - 多语言旅行助手</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- 顶部导航栏 -->
    <header>
        <h1>多语言旅行助手</h1>
        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="learning.html">学习中心</a></li>
                <li><a href="translation.html">翻译</a></li>
                <li><a href="culture.html" class="active">文化知识库</a></li>
                <li><a href="map.html">离线地图</a></li>
                <li><a href="travel-plan.html">旅行计划</a></li>
                <li><a href="offline-content.html">离线内容</a></li>
                <li><a href="profile.html">个人资料</a></li>
                <li><a href="settings.html">设置</a></li>
            </ul>
        </nav>
    </header>

    <!-- 侧边导航栏 -->
    <aside class="side-nav">
        <ul>
            <li>
                <a href="index.html">
                    <img src="images/home.svg" alt="首页图标">
                    <span>首页</span>
                </a>
            </li>
            <li>
                <a href="learning.html">
                    <img src="images/book-open-bold.svg" alt="学习图标">
                    <span>学习</span>
                </a>
            </li>
            <li>
                <a href="translation.html">
                    <img src="images/vector_25_310.svg" alt="翻译图标">
                    <span>翻译</span>
                </a>
            </li>
            <li>
                <a href="culture.html" class="active">
                    <img src="images/globe-bold.svg" alt="文化图标">
                    <span>文化</span>
                </a>
            </li>
            <li>
                <a href="map.html">
                    <img src="images/vector_25_317.svg" alt="地图图标">
                    <span>地图</span>
                </a>
            </li>
            <li>
                <a href="offline-content.html">
                    <img src="images/vector_25_324.svg" alt="离线内容图标">
                    <span>离线</span>
                </a>
            </li>
            <li>
                <a href="settings.html">
                    <img src="images/vector_25_331.svg" alt="设置图标">
                    <span>设置</span>
                </a>
            </li>
        </ul>
    </aside>

    <!-- 内容区 -->
    <main class="content culture-content">
        <h1 class="page-title">文化知识库</h1>
        
        <div class="culture-search">
            <input type="text" id="culture-search-input" placeholder="搜索文化知识、历史背景或地点">
            <button id="culture-search-btn" class="primary-btn">
                <img src="images/placeholder.svg" alt="搜索" width="16" height="16">
                搜索
            </button>
        </div>
        
        <div class="culture-categories">
            <div class="category-card" data-category="history">
                <img src="images/placeholder.svg" alt="历史背景">
                <h3>历史背景</h3>
                <p>了解各地区的历史演变和重要事件</p>
            </div>
            <div class="category-card" data-category="customs">
                <img src="images/placeholder.svg" alt="文化习俗">
                <h3>文化习俗</h3>
                <p>探索当地礼仪、禁忌和社交规范</p>
            </div>
            <div class="category-card" data-category="language">
                <img src="images/placeholder.svg" alt="语言文化">
                <h3>语言文化</h3>
                <p>理解语言背后的文化内涵和历史渊源</p>
            </div>
            <div class="category-card" data-category="people">
                <img src="images/placeholder.svg" alt="历史人物">
                <h3>历史人物</h3>
                <p>认识对当地历史文化有重要影响的人物</p>
            </div>
        </div>
        
        <div class="culture-content-area">
            <div id="culture-loading" class="loading-container">
                <div class="loading-spinner"></div>
                <p>正在加载文化内容...</p>
            </div>
            
            <div id="culture-results" class="culture-results">
                <!-- 内容将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <div class="popular-queries">
            <h3>热门文化查询</h3>
            <div class="query-tags">
                <span class="query-tag" data-query="日本茶道文化">日本茶道文化</span>
                <span class="query-tag" data-query="法国餐桌礼仪">法国餐桌礼仪</span>
                <span class="query-tag" data-query="意大利文艺复兴">意大利文艺复兴</span>
                <span class="query-tag" data-query="泰国传统节日">泰国传统节日</span>
                <span class="query-tag" data-query="埃及金字塔历史">埃及金字塔历史</span>
            </div>
        </div>
    </main>

    <footer>
        <p>&copy; 2025 多语言旅行助手 | 版本 1.0</p>
    </footer>

    <script src="script.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 隐藏加载动画
            document.getElementById('culture-loading').style.display = 'none';
            
            // 搜索功能
            document.getElementById('culture-search-btn').addEventListener('click', () => {
                const query = document.getElementById('culture-search-input').value.trim();
                if (query) searchCultureInfo(query);
            });
            
            // 回车键搜索
            document.getElementById('culture-search-input').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const query = e.target.value.trim();
                    if (query) searchCultureInfo(query);
                }
            });
            
            // 类别卡片点击
            document.querySelectorAll('.category-card').forEach(card => {
                card.addEventListener('click', () => {
                    const category = card.dataset.category;
                    let query = '';
                    
                    switch(category) {
                        case 'history': query = '世界主要文明的历史演变'; break;
                        case 'customs': query = '不同国家的文化礼仪和禁忌'; break;
                        case 'language': query = '语言背后的文化含义和表达方式'; break;
                        case 'people': query = '对世界历史有重大影响的历史人物'; break;
                    }
                    
                    searchCultureInfo(query);
                });
            });
            
            // 热门查询标签点击
            document.querySelectorAll('.query-tag').forEach(tag => {
                tag.addEventListener('click', () => {
                    searchCultureInfo(tag.dataset.query);
                });
            });
            
            // 初始加载一些默认内容
            searchCultureInfo('世界主要文化差异和礼仪指南');
        });
        
        // 搜索文化信息
        async function searchCultureInfo(query) {
            // 显示加载动画
            const cultureLoading = document.getElementById('culture-loading');
            const cultureResults = document.getElementById('culture-results');
            cultureLoading.style.display = 'flex';
            cultureResults.innerHTML = '';
            
            try {
                // 调用文化信息API
                const response = await fetch('/api/culture', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        query: query
                    }),
                });
                
                const data = await response.json();
                
                // 隐藏加载动画
                cultureLoading.style.display = 'none';
                
                // 显示结果
                if (data.error) {
                    cultureResults.innerHTML = `
                        <div class="error-message">
                            <p>${data.error}</p>
                            <button class="secondary-btn" onclick="retrySearch('${query}')">重试</button>
                        </div>
                    `;
                } else {
                    cultureResults.innerHTML = `
                        <div class="culture-result-card">
                            <h2>${query}</h2>
                            <div class="culture-content-text">
                                ${formatCultureContent(data.culture_info)}
                            </div>
                            <div class="culture-actions">
                                <button class="secondary-btn" onclick="translateCultureContent(this)">
                                    <img src="images/placeholder.svg" alt="翻译" width="16" height="16">
                                    翻译内容
                                </button>
                                <button class="secondary-btn" onclick="saveCultureContent(this)">
                                    <img src="images/placeholder.svg" alt="保存" width="16" height="16">
                                    保存离线
                                </button>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                // 隐藏加载动画
                cultureLoading.style.display = 'none';
                
                // 显示错误
                cultureResults.innerHTML = `
                    <div class="error-message">
                        <p>获取文化信息失败: ${error.message}</p>
                        <button class="secondary-btn" onclick="retrySearch('${query}')">重试</button>
                    </div>
                `;
            }
        }
        
        // 格式化文化内容
        function formatCultureContent(content) {
            // 将文本中的段落转换为HTML段落
            return content.split('\n').map(para => {
                if (para.trim() === '') return '';
                return `<p>${para}</p>`;
            }).join('');
        }
        
        // 翻译文化内容
        window.translateCultureContent = async function(button) {
            const contentElement = button.closest('.culture-result-card').querySelector('.culture-content-text');
            const originalContent = contentElement.getAttribute('data-original') || contentElement.innerHTML;
            
            // 如果已经翻译过，切换回原文
            if (contentElement.getAttribute('data-original')) {
                contentElement.innerHTML = originalContent;
                contentElement.removeAttribute('data-original');
                button.innerHTML = '<img src="images/placeholder.svg" alt="翻译" width="16" height="16"> 翻译内容';
                return;
            }
            
            // 保存原始内容
            contentElement.setAttribute('data-original', originalContent);
            
            // 显示加载状态
            button.textContent = '翻译中...';
            
            try {
                // 提取纯文本
                const textContent = contentElement.textContent;
                
                // 调用翻译API
                const response = await fetch('/api/translate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: textContent,
                        source_lang: 'zh',
                        target_lang: 'en'
                    }),
                });
                
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 格式化翻译结果
                contentElement.innerHTML = formatCultureContent(data.translated_text);
                
                // 更新按钮
                button.innerHTML = '<img src="images/placeholder.svg" alt="原文" width="16" height="16"> 显示原文';
            } catch (error) {
                // 恢复原始内容
                contentElement.innerHTML = originalContent;
                contentElement.removeAttribute('data-original');
                
                // 显示错误
                alert(`翻译失败: ${error.message}`);
                button.innerHTML = '<img src="images/placeholder.svg" alt="翻译" width="16" height="16"> 翻译内容';
            }
        };
        
        // 保存文化内容到离线
        window.saveCultureContent = function(button) {
            const card = button.closest('.culture-result-card');
            const title = card.querySelector('h2').textContent;
            const content = card.querySelector('.culture-content-text').innerHTML;
            
            // 获取已保存的离线文化内容
            let savedContent = JSON.parse(localStorage.getItem('offlineCultureContent') || '[]');
            
            // 检查是否已保存
            const existingIndex = savedContent.findIndex(item => item.title === title);
            if (existingIndex !== -1) {
                // 更新现有内容
                savedContent[existingIndex].content = content;
                savedContent[existingIndex].date = new Date().toISOString();
            } else {
                // 添加新内容
                savedContent.push({
                    title: title,
                    content: content,
                    date: new Date().toISOString()
                });
            }
            
            // 保存到本地存储
            localStorage.setItem('offlineCultureContent', JSON.stringify(savedContent));
            
            // 更新按钮状态
            button.textContent = '已保存';
            setTimeout(() => {
                button.innerHTML = '<img src="images/placeholder.svg" alt="保存" width="16" height="16"> 保存离线';
            }, 2000);
        };
        
        // 重试搜索
        window.retrySearch = function(query) {
            searchCultureInfo(query);
        };
    </script>
</body>
</html>